<template>
  <div class="storage-stock-container">
    <!-- 上半部分：库存数量占比饼图 -->
    <div class="chart-section">
      <h3 class="chart-title">库存数量占比</h3>
      <div class="chart-content">
        <div class="chart-wrapper">
          <v-chart 
            class="chart" 
            :option="chartOption" 
            :autoresize="true"
            @click="handleChartClick"
          />
        </div>
        <div class="legend-section">
          <div class="legend-item" v-for="(item, index) in warehouseData" :key="index">
            <div class="legend-color" :style="{ backgroundColor: colors[index] }"></div>
            <div class="legend-text">
              <span class="warehouse-name">{{ item.name }}</span>
              <span class="warehouse-quantity">{{ item.quantity }} 件</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 下半部分：入库排名表格 -->
    <div class="ranking-section">
      <h3 class="ranking-title">入库排名</h3>
      <div class="ranking-content">
        <div class="table-wrapper">
          <table class="ranking-table">
            <thead>
              <tr>
                <th class="rank-header">排名</th>
                <th class="product-header">货品名称</th>
                <th class="quantity-header">数量</th>
                <th class="amount-header">金额</th>
                <th class="count-header">入库次数</th>
              </tr>
            </thead>
            <tbody>
              <tr 
                v-for="(item, index) in rankingData" 
                :key="index"
                :class="{ 'top-rank': index < 3 }"
              >
                <td class="rank-cell" :class="{ 'top-rank-cell': index < 3 }">
                  {{ index + 1 }}
                </td>
                <td class="product-cell">{{ item.product }}</td>
                <td class="quantity-cell">{{ item.num }}</td>
                <td class="amount-cell">¥{{ item.price.toFixed(2) }}</td>
                <td class="count-cell">{{ item.count }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <!-- 连接状态指示器 -->
    <div class="connection-status" :class="{ connected: isConnected }">
      <span class="status-dot"></span>
      <span class="status-text">{{ isConnected ? '实时连接中' : '连接中...' }}</span>
    </div>
    
    <!-- 调试信息 -->
    <div class="debug-info" v-if="!isConnected">
      <p class="debug-text">SignalR 连接失败，使用 HTTP API 获取数据</p>
      <p class="debug-text">请检查后端服务是否正常运行在 http://localhost:5021</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { signalRService, type WarehouseData } from '@/http/signalr'
import axios from 'axios'
import { http } from '@/axios/axiosHelpers'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent
])

// 定义排名数据接口
interface RankingItem {
  product: string
  num: number
  price: number
  count: number
}

// 响应式数据 - 仓库数据（饼图用）
const warehouseData = ref<WarehouseData[]>([])

// 响应式数据 - 排名数据（表格用）
const rankingData = ref<RankingItem[]>([])

// 连接状态
const isConnected = ref(false)

// 图表颜色配置
const colors = [
  '#91cc75', '#5470c6', '#ee6666', '#73c0de', 
  '#3ba272', '#fc8452', '#9a60b4'
]

// 计算总库存
const totalQuantity = computed(() => {
  return warehouseData.value.reduce((sum, item) => sum + item.quantity, 0)
})

// 图表配置
const chartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  series: [
    {
      name: '库存数量',
      type: 'pie',
      radius: ['50%', '80%'],
      center: ['50%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: warehouseData.value.map((item, index) => ({
        value: item.quantity,
        name: item.name,
        itemStyle: {
          color: colors[index]
        }
      }))
    },
    {
      name: '中心文字',
      type: 'pie',
      radius: ['0%', '45%'],
      center: ['50%', '50%'],
      label: {
        show: true,
        position: 'center',
        formatter: () => {
          return `{total|${totalQuantity.value}}\n{label|总库存}`
        },
        rich: {
          total: {
            fontSize: 24,
            fontWeight: 'bold',
            color: '#333',
            lineHeight: 30
          },
          label: {
            fontSize: 14,
            color: '#666',
            lineHeight: 20
          }
        }
      },
      data: [{
        value: 1,
        name: 'center',
        itemStyle: {
          color: 'transparent'
        }
      }]
    }
  ]
}))

// 处理排名数据更新
const handleRankingUpdate = (data: RankingItem[]) => {
  console.log('收到入库排名数据更新:', data)
  rankingData.value = data
}

// 处理库存数据更新
const handleStorageStockUpdate = (data: WarehouseData[]) => {
  console.log('收到库存数据更新:', data)
  warehouseData.value = data.map(item => ({
    ...item,
    name: getWarehouseName(item.storageId)
  }))
}

// 根据storageId获取仓库名称
const getWarehouseName = (storageId: number): string => {
  const warehouseNames = [
    '仓库一', '仓库二', '仓库三', '仓库四', 
    '仓库五', '仓库六', '仓库七', '仓库八'
  ]
  return warehouseNames[storageId - 1] || `仓库${storageId}`
}

// 处理图表点击事件
const handleChartClick = (params: any) => {
  console.log('点击了:', params.name, '数量:', params.value)
}

// 从HTTP API获取初始数据
const loadInitialData = async () => {
  try {
    // 获取排名数据
    const rankingResponse = await http.get("/lssueread/api/ChatHub/GetStocking")
    if (rankingResponse.data.code === 200) {
      rankingData.value = rankingResponse.data.data
      console.log('从HTTP API获取到排名数据:', rankingResponse.data.data)
    }
    
    // 获取库存数据
    const stockResponse = await http.get("/lssueread/api/ChatHub/GetStorageStock")
    if (stockResponse.data.code === 200) {
      warehouseData.value = stockResponse.data.data.map((item: WarehouseData) => ({
        ...item,
        name: getWarehouseName(item.storageId)
      }))
      console.log('从HTTP API获取到库存数据:', stockResponse.data.data)
    }
  } catch (error) {
    console.error('从HTTP API获取数据失败:', error)
  }
}

// 初始化 SignalR 连接
const initSignalRConnection = async () => {
  try {
    // 监听连接状态变化
    signalRService.onConnectionStateChange((connected: boolean) => {
      isConnected.value = connected
      console.log('连接状态变化:', connected ? '已连接' : '未连接')
    })

    const success = await signalRService.initConnection()
    if (success) {
      // 监听排名数据更新
      signalRService.on('ReceiveStockingData', handleRankingUpdate)
      // 监听库存数据更新
      signalRService.on('ReceiveStorageStock', handleStorageStockUpdate)
      
      // 请求初始数据
      try {
        await signalRService.invoke('GetStocking')
        await signalRService.invoke('GetStorageStock')
        console.log('通过 SignalR 请求初始数据成功')
      } catch (invokeError) {
        console.warn('SignalR 调用失败，使用 HTTP API:', invokeError)
        await loadInitialData()
      }
    } else {
      // SignalR连接失败，使用HTTP API
      console.log('SignalR连接失败，使用HTTP API')
      await loadInitialData()
    }
  } catch (error) {
    console.error('初始化 SignalR 连接失败:', error)
    // 使用HTTP API作为备用方案
    await loadInitialData()
  }
}

// 组件挂载时初始化
onMounted(async () => {
  await initSignalRConnection()
})

// 组件卸载时清理连接
onUnmounted(() => {
  signalRService.off('ReceiveStockingData', handleRankingUpdate)
  signalRService.off('ReceiveStorageStock', handleStorageStockUpdate)
  signalRService.stop()
  isConnected.value = false
})
</script>

<style scoped>
.storage-stock-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
}

/* 饼图部分样式 */
.chart-section {
  margin-bottom: 40px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  text-align: left;
}

.chart-content {
  display: flex;
  align-items: center;
  gap: 40px;
}

.chart-wrapper {
  flex: 1;
  position: relative;
}

.chart {
  width: 100%;
  height: 400px;
}

.legend-section {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.warehouse-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.warehouse-quantity {
  font-size: 12px;
  color: #666;
}

.ranking-section {
  width: 100%;
}

.ranking-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  text-align: left;
}

.ranking-content {
  width: 100%;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
}

.ranking-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ranking-table thead {
  background: #f8f9fa;
}

.ranking-table th {
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e9ecef;
  font-size: 14px;
}

.ranking-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f3f4;
  font-size: 14px;
  color: #333;
}

.ranking-table tbody tr:hover {
  background-color: #f8f9fa;
}

/* 排名列样式 */
.rank-header {
  width: 80px;
}

.rank-cell {
  font-weight: 600;
  text-align: center;
}

.top-rank-cell {
  background: #1890ff;
  color: #fff;
  border-radius: 4px;
}

/* 货品名称列 */
.product-header {
  min-width: 200px;
}

.product-cell {
  font-weight: 500;
}

/* 数量列 */
.quantity-header {
  width: 100px;
  text-align: center;
}

.quantity-cell {
  text-align: center;
  font-weight: 500;
}

/* 金额列 */
.amount-header {
  width: 120px;
  text-align: center;
}

.amount-cell {
  text-align: center;
  color: #52c41a;
  font-weight: 500;
}

/* 入库次数列 */
.count-header {
  width: 120px;
  text-align: center;
}

.count-cell {
  text-align: center;
  color: #666;
}

/* 前三名特殊样式 */
.top-rank {
  background-color: #f0f8ff;
}

.top-rank:hover {
  background-color: #e6f7ff;
}

.connection-status {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 12px;
  color: #666;
}

.connection-status.connected {
  background: #e8f5e8;
  color: #52c41a;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  animation: pulse 2s infinite;
}

.connection-status.connected .status-dot {
  background: #52c41a;
  animation: none;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .legend-section {
    flex: none;
    width: 100%;
  }
  
  .chart {
    height: 300px;
  }
  
  .ranking-table {
    font-size: 12px;
  }
  
  .ranking-table th,
  .ranking-table td {
    padding: 8px 12px;
  }
  
  .connection-status {
    position: static;
    margin-top: 20px;
    justify-content: center;
  }
}

.debug-info {
  margin-top: 20px;
  padding: 15px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
}

.debug-text {
  margin: 5px 0;
  font-size: 14px;
  color: #856404;
}
</style>
